package com.report.socket;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.report.dto.response.MemberRes;
import com.report.dto.response.OrderRes;
import com.zmh.framework.redis.RedisCache;
import com.zmh.framework.util.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/8/4 19:23
 */
@Component
@ServerEndpoint("/paySocket/{orderNo}")
@Slf4j
@SaIgnore
@AllArgsConstructor
public class PaySocketServer {

     private final static Map<String, Session> clients = MapUtil.newConcurrentHashMap();


    public void remove(String orderNo){
        if(clients.containsKey(orderNo)){
            clients.remove(orderNo);
        }

    }

    @OnOpen
    public void onOpen(Session session, @PathParam("orderNo") String orderNo){
        if(clients.containsKey(orderNo)){
            clients.remove(orderNo);
        }
        clients.put(orderNo,session);
        log.info("onOpen:{}",session.getId());
    }


    @OnClose
    public void onClose(@PathParam("orderNo") String orderNo){
        remove(orderNo);
    }

    @OnMessage
    public void onMessage(String message){
        log.info("onMessage:{}",message);
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        log.error("onError:{}",session.getId(),throwable);
    }


    public void sendMessage(OrderRes orderRes){
        try {
            Session session = clients.get(orderRes.getOrderNum());
            session.getBasicRemote().sendText(JSON.toJSONString(Result.successResult(orderRes)));
        } catch (IOException e) {
            log.error("error:{}",e.getMessage(),e);
        }
    }
}
